package com.worksystem.Common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.worksystem.entity.Roles;
import com.worksystem.entity.User;
public class MyhandlerInterceptor implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		//把ServletRequest和ServletResponse转换成真正的类型
        HttpServletRequest req = (HttpServletRequest)request;
        HttpSession session = req.getSession();
        //由于web.xml中设置Filter过滤全部请求，可以排除不需要过滤的url
        String requestURI = req.getRequestURI();
       // System.out.println(requestURI);
       //资源文件允许访问
        if(requestURI.contains("assets")){
        	 chain.doFilter(request, response);
        	 return;
        }
        //用户模块允许访问
        if(requestURI.contains("user")){
            chain.doFilter(request, response);
            System.out.println("访问登录页面");
            return;
        }
        //判断用户是否登录，进行页面的处理
        if(null == session.getAttribute(Constant.SESSION_USER)){
            //未登录用户，重定向到登录页面
            ((HttpServletResponse)response).sendRedirect("/WorkSystem/user/login");
           System.out.println("登录页面跳转");
            return;
        } else {
            //已登录用户，允许访问并检查权限
        	System.out.println(requestURI);
        	if(checkpermission((User)session.getAttribute(Constant.SESSION_USER), requestURI)){
                chain.doFilter(request, response);
        	}else{
        		 ((HttpServletResponse)response).sendRedirect("/WorkSystem/common/nopower");
        		 chain.doFilter(request, response);
        	}
        }
	}

	public boolean checkpermission(User user,String url){
		Roles  role = user.getRole();
		if(url.contains("manage")){
			if(role.getModules().contains("manage"))
			return true;
			else
			return false;
		}
		else
		return true;
	}
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

}
